<?php

class Action_Community_DeleteTdi extends RL_Handler
{
	public function process ()
	{	
		$aa = $this->module->aa;
		$aa->getInfo();
		
		if ($aa->acl_data['role']['name']!="moderator") {
			$view = $this->rh->views->findByName('accessdnd');
			$view->data = $aa->template_data;
			$this->rh->response->setContent( $view );
			
			return;
		}

		$this->ctx->db->begin();
		$rs = $this->ctx->store->find( "objects where tdi.oid=:0 limit 0,1", array($aa->acl_data['tdi_oid']) );
		$obj = $rs->next();
		$obj->is_deleted = 1;
		$obj->save();
		
		// удалим сообщество из acl таблиц
		$aa->delete( $aa->acl_data['tdi_oid'] );
		
		if (!$this->ctx->db->isErrorInTransaction()) {
										
			$this->ctx->db->end();
			
			$this->addEventToItems("delete_item", $aa->acl_data['tdi_oid']);
			$this->addEventToComments("delete_comment", $aa->acl_data['tdi_oid']);
			
			$view = $this->rh->views->findByName('deletetdi_success');
			$view->data = $aa->template_data;
			
		} else {
			$this->ctx->db->rollback();
			$this->rh->response->setContent("Ошибка при запросе в БД.");
			return;
		}
		
		$this->rh->response->setContent($view);
	} // end of function process
	
	
	private function addEventToItems($event_name, $tdi_oid) {
		$prefix = $this->ctx->db->db_prefix;
		$rs = $this->ctx->store->findSQL(
		"SELECT {$prefix}objects.*, ao.openid FROM {$prefix}objects
		INNER JOIN {$prefix}class_allfeed af ON af.oid = {$prefix}objects.oid
		INNER JOIN {$prefix}class_user u ON u.oid = af.posted_by_id
		INNER JOIN {$prefix}class_auth_openid ao ON ao.oid = u.oid
		WHERE af.tdi_oid = ".$tdi_oid);

		while ($fitem = $rs->next()) {
			$row = $rs->rs->current();
			$this->ctx->logger->event(new Event(time(), $event_name, $row['openid'], $fitem->id));
		}

	}

	private function addEventToComments($event_name, $tdi_oid) {
		$prefix = $this->ctx->db->db_prefix;
		$rs = $this->ctx->store->findSQL(
		"SELECT {$prefix}objects.*, ao.openid, af.oid as item_oid FROM {$prefix}objects
		INNER JOIN {$prefix}class_comment c ON c.oid = {$prefix}objects.oid
		INNER JOIN {$prefix}class_allfeed af ON af.oid = c.item_oid
		INNER JOIN {$prefix}class_user u ON u.oid = af.posted_by_id
		INNER JOIN {$prefix}class_auth_openid ao ON ao.oid = u.oid
		WHERE af.tdi_oid = ".$tdi_oid." AND {$prefix}objects.is_deleted = 0"
		);

		while ($fc = $rs->next()) {
			$row = $rs->rs->current();
			$this->ctx->logger->event(new Event(time(), $event_name, $row['openid'], $fc->id));
		}

	}

}

